package com.dx.VegetableOxygenBarBackEnd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dx.VegetableOxygenBarBackEnd.common.BaseResponse;
import com.dx.VegetableOxygenBarBackEnd.common.ErrorCode;
import com.dx.VegetableOxygenBarBackEnd.common.ResultUtils;
import com.dx.VegetableOxygenBarBackEnd.exception.BusinessException;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.Messages;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.User;
import com.dx.VegetableOxygenBarBackEnd.service.MessagesService;
import com.dx.VegetableOxygenBarBackEnd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@RestController
@RequestMapping("/messages")
public class MessagesController {

    @Autowired
    private MessagesService messagesService;
    @Resource
    private UserService userService;

    /**
     * 发送消息
     * @param message
     * @return
     */
    @PostMapping("/send")
    public String sendMessage(@RequestBody Messages message) {
        message.setTimestamp(new Date());
        messagesService.save(message);
        return "Message sent successfully";
    }

    /**
     * 获取未读信息
     * @param receiverId
     * @return
     */
    @GetMapping("/unread/{receiverId}")
    public List<Messages> getUnreadMessages(@PathVariable Integer receiverId) {
        return messagesService.lambdaQuery()
                .eq(Messages::getReceiverId, receiverId)
                .eq(Messages::getIsRead, 0)
                .list();
    }

    /**
     * 标记信息为已读
     * @param messageIds
     * @return
     */
    @PostMapping("/markAsRead")
    public String markAsRead(@RequestBody List<Integer> messageIds) {
        List<Messages> messages = messagesService.listByIds(messageIds);
        messages.forEach(msg -> msg.setIsRead(1));
        messagesService.updateBatchById(messages);
        return "Messages marked as read";
    }

    /**
     * 获取用户的所有聊天用户
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/getList")
    public BaseResponse<List<User>> getMessages(HttpServletRequest httpServletRequest) {

        User loginUser = userService.getLoginUser(httpServletRequest);

        // 查询与当前用户有过聊天记录的消息
        QueryWrapper<Messages> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiverId", loginUser.getId());  // 查询接收者为当前用户的消息
        List<Messages> messagesList = messagesService.list(queryWrapper);

        if (CollectionUtils.isEmpty(messagesList)) {
            return ResultUtils.success(new ArrayList<>());  // 如果没有消息，返回空列表而不是抛出异常
        }

        // 获取与当前用户有过聊天的用户ID，并排除当前用户自身的ID
        Set<Integer> chattedUserIds = messagesList.stream()
                .map(Messages::getSenderId)  // 只获取发送者ID
                .filter(id -> !Objects.equals(id, loginUser.getId())) // 排除当前用户自身
                .collect(Collectors.toSet());

        if (chattedUserIds.isEmpty()) {
            return ResultUtils.success(new ArrayList<>());
        }

        // 查询与当前用户有过聊天的用户信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", chattedUserIds);
        List<User> chattedUsers = userService.list(userQueryWrapper);

        // 查询未读消息数量
        Map<Integer, Long> unreadMessageCountMap = messagesService.list(new QueryWrapper<Messages>()
                        .eq("isRead", 0)
                        .eq("receiverId", loginUser.getId()))  // 查询未读消息
                .stream()
                .collect(Collectors.groupingBy(Messages::getSenderId, Collectors.counting()));

        // 将未读消息数量存入每个用户的 noReadNum 中
        for (User user : chattedUsers) {
            // 检查用户ID和未读消息映射表的ID是否一致
            Long noReadNum = unreadMessageCountMap.getOrDefault(user.getId().intValue(), 0L);  // 确保类型一致
            user.setNoReadNum(noReadNum.intValue());  // 设置未读消息数量
        }

        // 按未读消息数量降序排序
        List<User> filteredUsers = chattedUsers.stream()
                .sorted((u1, u2) -> Integer.compare(u2.getNoReadNum(), u1.getNoReadNum())) // 按未读消息数量降序排序
                .collect(Collectors.toList());

        return ResultUtils.success(filteredUsers);
    }



}
